﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Threading;

namespace TDSM_GUI
{
    public partial class Form1 : Form
    {
        //Public variables
        Process proc = new Process();

        public Form1()
        {
            InitializeComponent();
            ipLabel.Text += " " + GetIP();
            ReadProperties();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (!File.Exists(Application.StartupPath + "/server.properties"))
            {
                MessageBox.Show("This appears to be the first time running TDSM. Please go to the main menu and select SERVER->Initialize TDSM", "Setup Server", MessageBoxButtons.OK, MessageBoxIcon.Information);
                tabControl1.SelectedTab = tabPage4;
            }
            else
            {
                tabControl1.SelectedTab = tabPage1;
            }

            

        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            BackgroundWorker bw = new BackgroundWorker();

            // this allows our worker to report progress during work
            bw.WorkerReportsProgress = true;

            // what to do in the background thread
            bw.DoWork += new DoWorkEventHandler(
            delegate(object o, DoWorkEventArgs args)
            {
                BackgroundWorker b = o as BackgroundWorker;

                // Create and read the Terraria_Server.exe console output
                
                proc.StartInfo.FileName = Application.StartupPath + "/Terraria_Server.exe";

                // set up input & output redirection
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.RedirectStandardInput = true;
                proc.EnableRaisingEvents = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.UseShellExecute = false;
                // see below for input &  output handler
                proc.ErrorDataReceived += proc_DataReceived;
                proc.OutputDataReceived += proc_DataReceived;

                proc.Start();

                proc.BeginErrorReadLine();
                proc.BeginOutputReadLine();

                proc.WaitForExit();

            });

            // what to do when progress changed (update the progress bar for example)
            bw.ProgressChanged += new ProgressChangedEventHandler(
            delegate(object o, ProgressChangedEventArgs args)
            {
                
            });

            // what to do when worker completes its task (notify the user)
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
            delegate(object o, RunWorkerCompletedEventArgs args)
            {
                consoleOutput.Text += "======================================================================================================" + Environment.NewLine;
    
                consoleOutput.Text += "TDSM GUI :: Completed";
            });

            bw.RunWorkerAsync();
        }

        void proc_DataReceived(object sender, DataReceivedEventArgs e)
        {
            // output will be in string e.Data
            consoleOutput.AppendText(Environment.NewLine + e.Data);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            proc.StandardInput.WriteLine(textBox2.Text);
        }

        public string GetIP()
        {
            string publicIP;
            HTTPGet req = new HTTPGet();
            req.Request("http://checkip.dyndns.org");
            string[] a = req.ResponseBody.Split(':');
            string a2 = a[1].Substring(1);
            string[] a3 = a2.Split('<');
            string a4 = a3[0];
            publicIP = a4;

            return publicIP;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (Process Proc in Process.GetProcesses())
            {
                if (Proc.ProcessName.Equals("Terraria_Server"))
                {
                    Proc.Kill();
                }
            }
        }

        private void menuItem5_Click(object sender, EventArgs e)
        {
            foreach (Process Proc in Process.GetProcesses())
            {
                if (Proc.ProcessName.Equals("Terraria_Server"))
                {
                    Proc.Kill();
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            proc.StandardInput.WriteLine("stop");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            proc.StandardInput.WriteLine("save-all");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            foreach (Process Proc in Process.GetProcesses())
            {
                if (Proc.ProcessName.Equals("Terraria_Server"))
                {
                    Proc.Kill();
                }
            }
        }

        public void ReadProperties()
        {
            try
            {
                textBox1.Text = File.ReadAllText(Application.StartupPath + "/server.properties");
            }
            catch
            {
                MessageBox.Show("server.properties file missing. Please initialize TDSM.", "Woops!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            File.WriteAllText(Application.StartupPath + "/server.properties", textBox1.Text);
            ReadProperties();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            webBrowser1.GoBack();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            webBrowser1.GoForward();
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            aboutTDSM aboutdsm = new aboutTDSM();
            aboutdsm.Show();
        }

        private void menuItem6_Click(object sender, EventArgs e)
        {
            tdsmGui tdsmgui = new tdsmGui();
            //tdsmgui.Show();
        }

        private void menuItem8_Click(object sender, EventArgs e)
        {
            foreach (Process Proc in Process.GetProcesses())
            {
                if (Proc.ProcessName.Equals("Terraria_Server"))
                {
                    Proc.Kill();
                }
            }
            Application.Exit();
        }

    }
}
